namespace RBAC.Write.Api.Application.Handler.BomHandler
{
    using MediatR;
    using Microsoft.Extensions.Logging;
    using RBAC.Domain.BomManage;
    using RBAC.ErrorCode;
    using RBAC.Interstructrue.Base;
    using RBAC.Write.Api.Application.Command.BomCommand;

    /// <summary>
    /// 编辑 BOM 明细 处理器（仅支持编辑：用量、序号）
    /// </summary>
    public class BomItemUpdateHandler : IRequestHandler<BomItemUpdateCommand, APIResult<int>>
    {
        private readonly IBaseRepository<BomItem> _bomItemRepo;
        private readonly ILogger<BomItemUpdateHandler> _logger;

        public BomItemUpdateHandler(
            IBaseRepository<BomItem> bomItemRepo,
            ILogger<BomItemUpdateHandler> logger)
        {
            _bomItemRepo = bomItemRepo;
            _logger = logger;
        }

        public Task<APIResult<int>> Handle(BomItemUpdateCommand request, CancellationToken cancellationToken)
        {
            var result = new APIResult<int>();
            try
            {
                cancellationToken.ThrowIfCancellationRequested();

                if (request.Id <= 0)
                    return Task.FromResult(new APIResult<int> { Code = APIEnums.Fail, Msg = "明细Id无效", Data = 0 });

                var entity = _bomItemRepo.GetFirstOrDefault("Id = @Id AND IsDeleted = 0", new { Id = request.Id });
                if (entity == null)
                    return Task.FromResult(new APIResult<int> { Code = APIEnums.Fail, Msg = "BOM明细不存在", Data = 0 });

                // 仅允许更新：Qty、Position
                if (!request.Qty.HasValue && !request.Position.HasValue)
                    return Task.FromResult(new APIResult<int> { Code = APIEnums.Fail, Msg = "请至少提供用量或序号之一", Data = 0 });

                if (request.Qty.HasValue)
                {
                    if (request.Qty.Value <= 0)
                        return Task.FromResult(new APIResult<int> { Code = APIEnums.Fail, Msg = "用量必须大于0", Data = 0 });
                    entity.Qty = request.Qty.Value;
                }
                if (request.Position.HasValue)
                    entity.Position = request.Position.Value;

                var affected = _bomItemRepo.Update(entity);
                result.Code = affected > 0 ? APIEnums.Success : APIEnums.Fail;
                result.Msg = affected > 0 ? "编辑BOM明细成功（仅更新用量/序号）" : "编辑BOM明细失败";
                result.Data = affected;
            }
            catch (OperationCanceledException)
            {
                _logger?.LogWarning("编辑BOM明细被取消");
                result.Code = APIEnums.Fail;
                result.Msg = "请求已取消";
                result.Data = 0;
            }
            catch (Exception ex)
            {
                _logger?.LogError(ex, "编辑BOM明细异常: {Message}", ex.Message);
                result.Code = APIEnums.Fail;
                result.Msg = "编辑BOM明细异常: " + ex.Message;
                result.Data = 0;
            }

            return Task.FromResult(result);
        }
    }
}
